package com.shujia.service;

import com.shujia.bean.Weibo;
import com.shujia.dao.WeiboDao;
import com.shujia.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

/**
 * @author yangjiming
 * @ClassName WeiboService
 * @Description
 * @create 2021-04-02 11:16
 */

@Service
public class WeiboService {
    @Autowired
    WeiboDao weiboDao;


    public Weibo queryWeiboById(Integer id) {

        //先查缓存，如果缓存中有数据直接返回
        String key = "weibo:" + id;
        Jedis jedis = null;
        try {
            //获取连接
            jedis = RedisUtil.getConnection();

            String text = jedis.get(key);
            if (text != null) {
                Weibo weibo = new Weibo();
                weibo.setId(id);
                weibo.setText(text);

                //更新过期时间
                jedis.expire(key, 10);
                System.out.println("缓存中有数据，直接返回");
                return weibo;
            }
        } catch (Exception e) {
            System.out.println("查询缓存失败");
        } finally {
            if (jedis != null)
                jedis.close();
        }

        //缓存中没有查数据库
        Weibo weibo = weiboDao.queryWeiboById(id);
        //将数据写入缓存

        try {
            jedis = RedisUtil.getConnection();
            jedis.set(key, weibo.getText());
            //更新过期时间
            jedis.expire(key, 10);
            System.out.println("查询数据库");

        } catch (Exception e) {
            System.out.println("插入数据失败");
        } finally {
            if (jedis != null)
                jedis.close();
        }

        return weibo;
    }
}
